package main

import (
	"fmt"
	"math/rand"
)

// 被迭代的元素（歌）
type Song struct {
	Name string
}

// 关键组件，定义迭代器，需要实现迭代方法和停止方法
type SongIterator interface {
	HasNext() bool
	Next() *Song
}

// 顺序播放器
type NormalIterator struct {
	songs []*Song
	index int
}

func (s *NormalIterator) HasNext() bool {
	return s.index < len(s.songs)
}

func (s *NormalIterator) Next() *Song {
	if s.HasNext() {
		song := s.songs[s.index]
		s.index++
		return song
	}
	return nil
}

// 随机播放器
type RandomIterator struct {
	songs []*Song
}

func (s *RandomIterator) HasNext() bool {
	return len(s.songs) > 0
}

func (s *RandomIterator) Next() *Song {
	if s.HasNext() {
		index := rand.Intn(len(s.songs))
		song := s.songs[index]
		s.songs = append(s.songs[:index], s.songs[index+1:]...)
		return song
	}
	return nil
}

// 歌单
type Playlist struct {
	songs []*Song
}

// 为歌单设置迭代器
func (p *Playlist) CreateIterator(mode string) SongIterator {
	switch mode {
	case "normal":
		return &NormalIterator{songs: p.songs}
	case "random":
		return &RandomIterator{songs: p.songs}
	default:
		return &NormalIterator{songs: p.songs}
	}
}

func main() {
	playlist := &Playlist{
		songs: []*Song{
			{"稻香"},
			{"简单爱"},
			{"安静"},
			{"倒带"},
			{"爱笑的眼睛"},
		},
	}
	iterator := playlist.CreateIterator("normal")
	for iterator.HasNext() {
		song := iterator.Next()
		fmt.Println(song.Name)
	}
	fmt.Println("-----------------")
	iterator = playlist.CreateIterator("random")
	for iterator.HasNext() {
		song := iterator.Next()
		fmt.Println(song.Name)
	}
}
